package com.partners.configure;

import com.partners.constant.ErrorMessageEnum;
import com.partners.model.ApiResult;
import com.partners.model.BusinessException;
import com.partners.utils.ApiResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.ResourceAccessException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author forever
 * @date 2018/7/6 14:48
 */
@RestControllerAdvice
public class GlobalControllerExceptionHandler {

    /** 日志记录器 */
    private final static Logger logger = LoggerFactory.getLogger(GlobalControllerExceptionHandler.class);

    private final static String LOG_TIPS = "【Controller异常处理器】";

    /** 空指针异常日志标题 */
    private final static String NPE_LOG_TIPS = LOG_TIPS + "【空指针异常】: ";

    /** 普通异常日志标题 */
    private final static String NORMAL_LOG_TIPS = LOG_TIPS + "【其他异常】: ";

    /**
     * 业务异常处理器
     * @param request HttpServletRequest
     * @param e Exception
     * @return ApiResult
     */
    @ExceptionHandler(BusinessException.class)
    public ApiResult businessExceptionHandler(HttpServletRequest request, BusinessException e) {
        return ApiResultUtil.failure(e.getBusinessMessage());
    }

    /**
     * 其他异常处理器
     * @param request HttpServletRequest
     * @param e Exception
     * @return ApiResult
     */
    @ExceptionHandler(Exception.class)
    public ApiResult defaultExceptionHandler(HttpServletRequest request, Exception e) {

        // 判断是否是空指针异常
        if (e instanceof NullPointerException) {
            logger.error(NPE_LOG_TIPS, e);
        } else if (e instanceof ResourceAccessException){
            //连接失败异常
            return ApiResultUtil.failure(ErrorMessageEnum.HOST_CONNECT_FALSE);
        } else {
            logger.error(NORMAL_LOG_TIPS, e);
        }

        return ApiResultUtil.failure(ErrorMessageEnum.SERVER_INTERNAL_ERROR);
    }

    /**
     * 主要处理使用@RequestBody时错误的json引起的Exception
     * @return ApiResult
     */
    @ExceptionHandler({HttpMessageNotReadableException.class, JSONException.class})
    public ApiResult errorJsonBodyHandler() {

        return ApiResultUtil.failure(ErrorMessageEnum.ERROR_JSON_INPUT);
    }

    /**
     * 处理请求方式错误引起的异常
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ApiResult errorRequestMethod() {
        return ApiResultUtil.failure(ErrorMessageEnum.ERROR_REQUEST_METHOD);
    }


}
